package org.csu.mypetstore.controller;

import org.csu.mypetstore.commonResponse.CommonResponse;
import org.csu.mypetstore.domin.Banner;
import org.csu.mypetstore.domin.Product;
import org.csu.mypetstore.service.impl.BannerServiceImpl;
import org.csu.mypetstore.service.impl.ProductServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/banners")
public class BannerController {
    @Autowired
    BannerServiceImpl bannerService;
    @Autowired
    ProductServiceImpl productService;
    @GetMapping("")
    public CommonResponse<List<Product>> getUserBanner(@RequestParam String username) throws IllegalAccessException {
        if(Objects.equals(username, "") || username == null){
            List<Product> originList = productService.getAllProduct();
            List<Product> resultList;
            //把源数据打乱
            Collections.shuffle(originList);
            //取前4个数据
            resultList = originList.subList(0,4);
            return CommonResponse.createForSuccess(resultList);
        }
        Banner banner = bannerService.getAllBanners(username);
        List<Product> result = new ArrayList<>();
        List<String> catList = banner.sort();
        for(int i =0;i<3;i++){
            List<Product> products = productService.getProductListByCategory(catList.get(i)).getData();
            result.addAll(products);
        }
        Collections.shuffle(result);
        result = result.subList(0,4);
        return CommonResponse.createForSuccess(result);
    }
    @PostMapping("")
    public CommonResponse<String> add(@RequestBody Banner banner){
        bannerService.addBanner(banner);
        return CommonResponse.createForSuccess();
    }
    @PutMapping("/{username}/{column}")
    public CommonResponse<String> addCount(@PathVariable String username,@PathVariable String column){
        bannerService.addCount(username,column);
        return CommonResponse.createForSuccess();
    }
    @DeleteMapping("/{username}")
    public CommonResponse<String> delete(@PathVariable String username){
        bannerService.deleteBanner(username);
        return CommonResponse.createForSuccess();
    }

}
